import serial
import random
import time
import datetime
import _thread
import json
import re
import contextvars
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from Utils.varStationConfig import VarStationConfig as varConfig
import threading
# urlArr = varConfig().urlArr
dutArr = varConfig().dutArr


mutex = _thread.allocate_lock()

# global DUT
# DUT = serial.Serial()
# DUT.port = str(urlArr[int(GroupIndex)])
# print("port url : ",DUT.port)
# # DUT.port = '/dev/cu.usbmodem14131202'
# # '/dev/cu.usbmodem1424202'
# DUT.baudrate = 115200
# DUT.timeout = 5
# DUT.bytesize = 8
# DUT.stopbits = 1
# DUT.parity = "N"

def openDUT(param):
    try:
        GroupIndex = threading.currentThread().getName()
        print("-----gggg----",GroupIndex)
        DUT = dutArr[int(GroupIndex)]
        print("Dut ========",DUT)
        DUT.open()
        if(DUT.isOpen()): 
            print("open serial sucess")
        else:
            print("open serial fail")
        return True
    except Exception as e:
        print("open dut error:",e)

def closeDUT(param):
    try:
        GroupIndex = threading.currentThread().getName()
        print("-----gggg----",GroupIndex)
        DUT = dutArr[int(GroupIndex)]
        if(DUT.isOpen()): 
            DUT.close()
            print("close serial sucess")
        else:
            print(" serial already closed")
        return True
    except Exception as e:
        print("close dut error:",e)

def sendDutCommand(paraTab):
    return sendDutCommandNumber(paraTab)
    # try:
        # mutex.acquire()
    #     GroupIndex = threading.currentThread().getName()
    #     DUT = dutArr[int(GroupIndex)]
    #     receive_msg = ""
    #     timeout = int(paraTab["Timeout"]) or 5
    #     AdditionalParameters = json.loads(paraTab["AdditionalParameters"])
    #     delimiter = AdditionalParameters["delimiter"] or ":-)"
    #     print("delimiter:",delimiter)
    #     expect=''
    #     try:
    #         expect = AdditionalParameters["expect"]
    #         print("expect:",expect)
    #     except Exception as e:
    #         print("expect key error :",e)
        
    #     # delimiter = ":-)"
    #     sendCommands = paraTab["Commands"] + "\n"
    #     print("send command :",sendCommands)
    #     DUT.timeout = timeout
    #     DUT.write(sendCommands.encode())
    #     time.sleep(0.5)
    #     startTime = datetime.datetime.now()
    #     data = DUT.read_all().decode()
    #     receive_msg += data

    #     # while (datetime.datetime.now()-startTime).seconds <= int(timeout):
    #     #     data = DUT.read_all().decode()
    #     #     receive_msg += data
    #     #     print("[0000recvData]---"+receive_msg)
    #     #     if (delimiter in receive_msg):
    #     #         print("[11recvData]---"+receive_msg)
    #     #         break
    #     #     time.sleep(0.5)
            

    #     print("[22recvData]---"+receive_msg)
    #     if sendCommands in "pmuadc --read all --avg 10":
    #         time.sleep(50)
    #     # mutex.release()
        
    #     if len(expect) == 0 :
    #         return True
    #     else:
    #         import re
    #         pattern = re.compile(expect)
    #         expectValue = pattern.findall(receive_msg)
    #         print("result:",expectValue)
    #         if len(expectValue) >0:
    #             print(f"execptvalue{sendCommands}")
    #             print('我是expectvalue1111111111',expectValue)
    #             print('我是typeexpectvalue1111111111',type(expectValue))
    #             return True
    #             # number = expectValue
    #             # return number
    #         else:
    #             return False
        
    #     # return receive_msg
    #     # return True                    
    # # except Exception as e:
    # #     print("<Error>[send commands fail]：", e)            



def sendDutCommandNumber(paraTab):
    # try:
        # mutex.acquire()
        def args_is_exist(AdditionalParameters,arg):
            if arg == "delimiter":
                delimiter = ":-)"
            if arg == "sleep":
                result = 0.2
            else:
                result = ""
            try:
                result = AdditionalParameters[arg]
               
            except:
                pass
            return result   

        GroupIndex = threading.currentThread().getName()
        DUT = dutArr[int(GroupIndex)]
        receive_msg = ""
        timeout = int(paraTab["Timeout"])
        AdditionalParameters = json.loads(paraTab["AdditionalParameters"])
        
        delimiter = args_is_exist(AdditionalParameters,"delimiter")
        sleep_time = args_is_exist(AdditionalParameters,"sleep")
        expect = args_is_exist(AdditionalParameters,"expect")
        print("sleep time:",sleep_time)
        print("timeout:",timeout)
        print("expect:",expect)

        DUT.timeout = timeout
        
        sendCommands = paraTab["Commands"] + "\n"
        
        print("send command :",sendCommands)
        DUT.write(sendCommands.encode())
        time.sleep(sleep_time)
        startTime = datetime.datetime.now()
        while True:
            data = DUT.read_all().decode()
            if data:
                receive_msg += data
            else:
                break

        print("[---recvData]---"+receive_msg)
        # mutex.release()
        
        if len(expect) == 0 :
            return True
        else:
            import re
            pattern = re.compile(expect)
            expectValue = pattern.findall(receive_msg)
            print("result:",expectValue)
            if len(expectValue) >0:
                # return True
                # number = float(expectValue[0])
                print('expectValue list is :',expectValue)
                print('expectValue list is :',expectValue[0])
                return expectValue[0]
            else:
                return False
        
def send(cmd):
    GroupIndex = threading.currentThread().getName()
    DUT = dutArr[int(GroupIndex)]
    if(DUT.isOpen()):
        cmd=cmd+'\n'
        DUT.write(cmd.encode('utf-8'))
        #print("send cmd sucess",cmd)
        DUT.flush()
    else:
        print("Serial port %s is closed", DUT.port)
    return True

def readResponse():
    GroupIndex = threading.currentThread().getName()
    DUT = dutArr[int(GroupIndex)]
    if DUT.isOpen:
            rxdata = bytearray(b'')
            timeBegin = time.time()
            while ((time.time() - timeBegin) < DUT.timeout):
                
                data = DUT.read_all()
                if data:
                    rxdata += bytearray(data)
            else:
                print("Command response timeout")
            
    else:
        raise RuntimeError("Serial port --- {} is closed".format(DUT.port) )
    rxdata = rxdata.decode('utf-8')
    # print(rxdata)
    return rxdata  

def Recive_data():
    GroupIndex = threading.currentThread().getName()
    DUT = dutArr[int(GroupIndex)]
    receive_msg = ""
    # delimiter = param.Timeout or ":-)"
    # while True:
    #     # data = DUT.readline().decode()
    #     data = DUT.read_all().decode()
    #     receive_msg += data
    #     if(delimiter in receive_msg):
    #         break
    try:
        receive_msg = DUT.read_all().decode()
        return receive_msg  
    except Exception as e:
        print('Recive_data error:',e)
        return False

def Recive_data_noDelimiter():
    GroupIndex = threading.currentThread().getName()
    DUT = dutArr[int(GroupIndex)]
    receive_msg = ""
    try:      
        receive_msg = DUT.read_all().decode()
        return receive_msg 
    except Exception as e:
        print('Recive_data_noDelimiter error:',e)
        print("------455555555555-------------")
        return False

def enterDiags(param):
    print(">>>>>>>>>>>>>>>>enter Diags<<<<<<<<<<<<<<<<<<<<")
    resp = ""
    for i in range(1000):
        send("\r")
        resp = Recive_data_noDelimiter()
        time.sleep(0.2)
        print("ssssss"+str(i)+":>>"+str(resp))
        if(":-)" in resp):
            print("111----",resp)
            break

        # else:
            # print("222----",resp)
            
        # send diags    
        send("diags")
        resp = readResponse()
        print(">>>>>>>>>>>>")
        print(resp)
        return True
        

function_dic = {
                "openDUT":openDUT,
                "send":send,
                "readResponse":readResponse,
                "enterDiags":enterDiags,
                "sendDutCommand":sendDutCommand,
                "closeDUT":closeDUT,
                "sendDutCommandNumber":sendDutCommandNumber
                }